package com.itboye.sunsunhome.www.aq;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.itboye.sunsunhome.www.aq.R;
import com.itboye.sunsunhome.www.aq.base.AppConfig;
import com.itboye.sunsunhome.www.aq.base.AqDevice;
import com.itboye.sunsunhome.www.aq.base.AqDeviceInfo;
import com.itboye.sunsunhome.www.aq.base.AqDeviceMessage;
import com.itboye.sunsunhome.www.aq.base.DensityUtil;
import com.itboye.sunsunhome.www.aq.base.MessageWhat;
import com.itboye.sunsunhome.www.aq.base.MyApplication;
import com.itboye.sunsunhome.www.aq.base.ServerInfoCallback;
import com.itboye.sunsunhome.www.aq.base.AqDeviceInfo.AqDeviceType;

/**
 * 日期：2015-05-11 1. 视频接收超时后自动关闭视频 2. 控制台标题更变为设备名称 日期：2015-05-12 1.
 * 网络状态更变后提示用户重新连接 2. 界面销毁后停止 mTimer，避免后台运行干扰下次操作 日期：2015-10-14 1. 添加广告JSON解析功能
 * 2. 状态栏取消显示广告，并恢复显示手动自动模式指示 日期：2015-11-20 1. JSON格式更改为数组格式，可存储多个内容，暂显示第一个内容
 */
@SuppressLint("NewApi")
public class DeviceConsoleActivity extends Activity implements
		SurfaceHolder.Callback {

	SwitchImageButton mButtonLamp;
	SwitchImageButton mButtonPump;
	SwitchImageButton mButtonUvLamp;
	SwitchImageButton mButtonMode;
	SwitchImageButton mButtonVideo;
	SwitchImageButton mButtonPhoto;
	TextView mTextViewInfo;
	TextView mTextViewTemp;
	TextView mTextViewPh;
	SurfaceView mSurfaceView;
	SurfaceHolder mSurfaceHolder;
	Canvas mCanvas;
	MyApplication mApp;
	Context mContext;
	Timer mTimer;
	Bitmap mPhoto;
	// 抑制控制
	private boolean mInhibit;
	// 自动状态同步
	private int mSyncMcuStateCount;
	// 视频超时计数器
	private int mVideoTimeoutCount;
	// 网络检测
	private String mNetIp;
	private int mNetTestCount;
	private boolean mReadyClose;
	// 广告
	private String mAd;
	private RelativeLayout moshi_weilianjie;// 设备未连接上时间显示
	private ImageView quanping;
	private RelativeLayout bottom;
	private AqDevice mDevice;
	TextView dengguangzhaoming;// 灯光照明功率，
	TextView chonglangshuibeng;// 冲浪水泵
	TextView ziwaixiandeng;// 紫外线灯
	TextView xunhuanshuibeng;// 循环水泵
	LinearLayout liearAq211;// AQ211
	ImageView back,setting;
	RelativeLayout top;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mApp = (MyApplication) getApplication();
		mApp.mDeviceConsoleUi = this;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_console);
//		getSupportActionBar().setDisplayShowHomeEnabled(false);
//		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//		getSupportActionBar().setDisplayShowTitleEnabled(true);

		mContext = this;
		mDevice = mApp.mCurrentDevice;
		back=(ImageView) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				closeUi();
			}
		});
		setting=(ImageView) findViewById(R.id.setting);
		setting.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent mainIntent = new Intent(DeviceConsoleActivity.this,
						DeviceOptionActivity.class);
				DeviceConsoleActivity.this.startActivity(mainIntent);
			}
		});
		top=(RelativeLayout) findViewById(R.id.top);
		dengguangzhaoming = (TextView) findViewById(R.id.dengguangzhaoming);
		chonglangshuibeng = (TextView) findViewById(R.id.chonglangshuibeng);
		ziwaixiandeng = (TextView) findViewById(R.id.ziwaixiandeng);
		xunhuanshuibeng = (TextView) findViewById(R.id.xunhuanshuibeng);
		liearAq211 = (LinearLayout) findViewById(R.id.aq211);
		if (mApp.mCurrentDevice.mDeviceInfo.mDeviceType == AqDeviceType.AQ211) {
			liearAq211.setVisibility(View.VISIBLE);
		} else {
			liearAq211.setVisibility(View.GONE);
		}
		quanping = (ImageView) findViewById(R.id.quanping);//全屏按钮
		bottom = (RelativeLayout) findViewById(R.id.bottom);
		moshi_weilianjie = (RelativeLayout) findViewById(R.id.moshi_weilianjie);
		moshi_weilianjie.setVisibility(View.VISIBLE);
		mButtonLamp = (SwitchImageButton) findViewById(R.id.device_console_imageButton1);
		mButtonPump = (SwitchImageButton) findViewById(R.id.device_console_imageButton2);
		mButtonUvLamp = (SwitchImageButton) findViewById(R.id.device_console_imageButton3);
		mButtonMode = (SwitchImageButton) findViewById(R.id.device_console_imageButton4);
		mButtonVideo = (SwitchImageButton) findViewById(R.id.device_console_imageButton5);
		mButtonPhoto = (SwitchImageButton) findViewById(R.id.device_console_imageButton6);
		mTextViewInfo = (TextView) findViewById(R.id.device_console_textView1);
		mTextViewTemp = (TextView) findViewById(R.id.device_console_textView8);
		mTextViewPh = (TextView) findViewById(R.id.device_console_textView9);
		mSurfaceView = (SurfaceView) findViewById(R.id.device_console_surfaceView1);

		mNetIp = null;
		mNetTestCount = 0;
		mReadyClose = false;
		mSyncMcuStateCount = 0;
		mVideoTimeoutCount = 0;
		mInhibit = false;
		showButtonState();
		showParameter();
		quanping.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
					setPortrat();
				} else {
					setLandScape();
				}
				// mSurfaceView.getHolder().setFixedSize(getWindowManager().getDefaultDisplay().getHeight(),
				// getWindowManager().getDefaultDisplay().getWidth());
			}
		});
		mButtonLamp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mButtonMode.getSelectState()) {
					// 自动模式下不可操作
					Toast.makeText(mContext, "请在手动模式下操作", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				delaySyncMcuState();
				boolean b = !mButtonLamp.getSelectState();
				mButtonLamp.setSelectState(b);
				mApp.mCurrentDevice.setRelays(AqDevice.Relays.Lamp, b);
			}
		});

		mButtonPump.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mButtonMode.getSelectState()) {
					Toast.makeText(mContext, "请在手动模式下操作", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				delaySyncMcuState();
				boolean b = !mButtonPump.getSelectState();
				mButtonPump.setSelectState(b);
				if (mApp.mCurrentDevice.mDeviceInfo.mDeviceType == AqDeviceInfo.AqDeviceType.AQ107) {
					mButtonUvLamp.setSelectState(b);
				}
				mApp.mCurrentDevice.setRelays(AqDevice.Relays.Pump, b);
			}
		});

		mButtonUvLamp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mButtonMode.getSelectState()) {
					Toast.makeText(mContext, "请在手动模式下操作", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				delaySyncMcuState();
				boolean b = !mButtonUvLamp.getSelectState();
				mButtonUvLamp.setSelectState(b);
				if (mApp.mCurrentDevice.mDeviceInfo.mDeviceType == AqDeviceInfo.AqDeviceType.AQ107) {
					mButtonPump.setSelectState(b);
				}
				mApp.mCurrentDevice.setRelays(AqDevice.Relays.UvLamp, b);
			}
		});

		mButtonMode.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				delaySyncMcuState();
				boolean b = !mButtonMode.getSelectState();
				mButtonMode.setSelectState(b);
				mApp.mCurrentDevice.setRelays(AqDevice.Relays.Mode, b);
				if (b) {
					mTextViewInfo.setText("当前模式：自动");
				} else {
					mTextViewInfo.setText("当前模式：手动");
				}
			}
		});

		mButtonVideo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				delaySyncMcuState();
				boolean b = !mButtonVideo.getSelectState();
				mButtonVideo.setSelectState(b);
				if (b) {
					mVideoTimeoutCount = 0;
					mApp.mCurrentDevice.setVideoStart(
							(short) AppConfig.Video_Frame_Count,
							(short) AppConfig.Video_Frame_Cycle, (short) 320,
							(short) 240);
					moshi_weilianjie.setVisibility(View.GONE);
				} else {
					mVideoTimeoutCount = 0;
					mApp.mCurrentDevice.setVideoStop();
					moshi_weilianjie.setVisibility(View.VISIBLE);
				}
			}
		});

		mButtonPhoto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				savePhoto(mPhoto);
			}
		});

		mSurfaceHolder = mSurfaceView.getHolder();
		mCanvas = null;
		mPhoto = null;
		mTimer = new Timer();
		mTimer.scheduleAtFixedRate(mTimerWorkTask, 100, 100);

		setTitle(mApp.mCurrentDevice.mDeviceInfo.mDeviceName);

		// TODO 广告读取功能
		mAd = "";
		mApp.mServerInfoRead.read(mApp.mCurrentDevice.mDeviceInfo.mDid,
				new ServerInfoCallback() {
					@Override
					public void callback(Object obj) {
						String retString = (String) obj;
						if (!TextUtils.isEmpty(retString)) {
							// 解析json
							try {
								List<String> list = JSON.parseArray(retString,
										String.class);
								String json = list.get(0);
								Map<String, String> map = JSON
										.parseObject(
												json,
												new TypeReference<Map<String, String>>() {
												});
								String tm = formatTime(map.get("tm"));
								String body = map.get("body");
								if (body.equalsIgnoreCase("")) {
									mAd = "";
								} else {
									mAd = tm + "\n" + body;
								}
								// 显示广告
								mCanvas = mSurfaceHolder.lockCanvas();
								if (mCanvas != null) {
									showAd(mAd);
									mSurfaceHolder.unlockCanvasAndPost(mCanvas);
								}
							} catch (Exception e) {
								// 错误的格式广告，保留处理
								mAd = "";
							}
						}
					}
				});
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

	}

	public static String formatTime(String user_time) {
		String ret_time = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date d = sdf.parse(user_time);
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			ret_time = sdf.format(d.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return ret_time;
	}

	private void showButtonState() {
		// 非抑制情况下可更新界面按键状态
		if (!mInhibit) {
			mButtonLamp.setSelectState(mApp.mCurrentDevice.mLampRelaysState);
			mButtonPump.setSelectState(mApp.mCurrentDevice.mPumpRelaysState);
			mButtonUvLamp
					.setSelectState(mApp.mCurrentDevice.mUvLampRelaysState);
			mButtonMode.setSelectState(mApp.mCurrentDevice.mAutoModeState);
			if (mApp.mCurrentDevice.mAutoModeState) {
				mTextViewInfo.setText("当前模式：自动");
			} else {
				mTextViewInfo.setText("当前模式：手动");
			}
		}
		// 任意状态下可更新
		mButtonVideo.setSelectState(mApp.mCurrentDevice.mVideoState);
	}

	private void showParameter() {
		double temp = (double) mApp.mCurrentDevice.mCurrentTemp / 10.0;
		double ph = (double) mApp.mCurrentDevice.mCurrentPh / 100.0;
		mTextViewTemp.setText(String.format("%.1f", temp) + "℃");
		mTextViewPh.setText(String.format("%.1f", ph));
		dengguangzhaoming.setText(mApp.mCurrentDevice.lightW + "w");
		chonglangshuibeng.setText(mApp.mCurrentDevice.shuiBengW + "w");
		ziwaixiandeng.setText(mApp.mCurrentDevice.ZiwaixianW + "w");
		xunhuanshuibeng.setText(mApp.mCurrentDevice.XunhuanW + "w");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_device_console, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.device_console_action_settings1) {
			Intent mainIntent = new Intent(DeviceConsoleActivity.this,
					DeviceOptionActivity.class);
			DeviceConsoleActivity.this.startActivity(mainIntent);
			return true;
		}
		if (id == android.R.id.home) {
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				setPortrat();
			} else {
				closeUi();
			}
		}
		return super.onOptionsItemSelected(item);
	}

	/*
	 * 横屏显示方法
	 */
	public void setLandScape() {
		bottom.setVisibility(View.GONE);
//		getSupportActionBar().hide();
		top.setVisibility(View.GONE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 设置为横屏
		quanping.setBackgroundResource(R.drawable.xiaoping);
	}

	/**
	 * 竖屏显示方法
	 */
	public void setPortrat() {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 设置为竖屏
		bottom.setVisibility(View.VISIBLE);
		top.setVisibility(View.VISIBLE);
//		getSupportActionBar().show();
		quanping.setBackgroundResource(R.drawable.quanping);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果是返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				setPortrat();
			} else {
				closeUi();
			}
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void closeDevice() {
		try {
			if (mApp.mCurrentDevice != null) {
				mApp.mCurrentDevice.closeConnect();
			}
		} catch (Exception e) {
		}
	}

	TimerTask mTimerWorkTask = new TimerTask() {
		@Override
		public void run() {
			Message msg = new Message();
			msg.what = MessageWhat.DeviceConsoleUiTimerMessage;
			mHandler.sendMessage(msg);
		}
	};

	private void delaySyncMcuState() {
		// 延迟同步，可避免按键出现闪烁状态
		mSyncMcuStateCount = 0;
		mInhibit = true;
	}

	private void syncMcuState() {
		// 立即同步一次状态
		mApp.mCurrentDevice.getState();
	}

	private String getRealPathFromURI(Uri contentUri) {
		String[] project = { MediaStore.Images.Media.DATA };
		CursorLoader loader = new CursorLoader(mContext, contentUri, project,
				null, null, null);
		Cursor cursor = loader.loadInBackground();
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private String saveImage(Bitmap bmp) {
		File appDir = new File(Environment.getExternalStorageDirectory(),
				"AQPicture");
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		Time timeNow = new Time();
		timeNow.set(System.currentTimeMillis());
		String timeInfo = String.valueOf(timeNow.year)
				+ String.format("%1$02d", timeNow.month + 1)
				+ String.format("%1$02d", timeNow.monthDay)
				+ String.format("%1$02d", timeNow.hour)
				+ String.format("%1$02d", timeNow.minute)
				+ String.format("%1$02d", timeNow.second);
		String fileName = mApp.mCurrentDevice.mDeviceInfo.mDeviceName + "_"
				+ timeInfo + ".jpg";
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (IOException e) {
			return null;
		}
		return file.getPath();
	}

	private String savePhoto(Bitmap photo) {
		// mApp.mCurrentDevice.linuxReboot(); // 遥控重启
		String fileName = null;
		if (photo == null) {
			Toast.makeText(mContext, "请先开启视频获取图像然后再试", Toast.LENGTH_SHORT)
					.show();
			return fileName;
		}
		fileName = saveImage(photo);
		if (fileName != null) {
			Toast.makeText(mContext, "照片已保存到：" + fileName, Toast.LENGTH_LONG)
					.show();
		} else {
			Toast.makeText(mContext, "照片保存失败，请检查是否存在SD卡", Toast.LENGTH_LONG)
					.show();
		}
		return fileName;
	}

	public static String getPsdnIp() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& inetAddress instanceof Inet4Address) {
						// if (!inetAddress.isLoopbackAddress() && inetAddress
						// instanceof Inet6Address) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (Exception e) {
		}
		return "";
	}

	private void closeUi() {
		try {
			mTimer.cancel();
			closeDevice();
			mApp.mDeviceConsoleUi = null;
			finish();
		} catch (Exception e) {
			mApp.mDeviceConsoleUi = null;
			finish();
		}
	}

	private void netTest() {
		if (mReadyClose) {
			return;
		}
		String ip = getPsdnIp();
		if (mNetIp == null) {
			mNetIp = ip;
		} else if (mNetIp.compareTo(ip) != 0) {
			mReadyClose = true;
			mNetIp = ip;
			new AlertDialog.Builder(mContext)
					.setTitle("连接出错")
					.setMessage("检测到网络状态发生改变，请重新连接")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									closeUi();
								}
							})
					.setOnKeyListener(new DialogInterface.OnKeyListener() {
						@Override
						public boolean onKey(DialogInterface dialog,
								int keyCode, KeyEvent event) {
							if (keyCode == KeyEvent.KEYCODE_BACK
									&& event.getRepeatCount() == 0) {
								closeUi();
							}
							return false;
						}
					}).show();
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MessageWhat.DeviceConsoleUiTimerMessage:
				// 100ms定时器周期
				// 检测网络
				if (++mNetTestCount >= 10) {
					mNetTestCount = 0;
					netTest();
				}
				// 数据同步
				if (++mSyncMcuStateCount >= 50) {
					// 5秒刷新
					mSyncMcuStateCount = 0;
					// 解除抑制
					mInhibit = false;
					// 同步状态
					syncMcuState();
				}
				// 视频超时控制
				if (mButtonVideo.getSelectState()) {
					if (++mVideoTimeoutCount >= (AppConfig.Video_Timeout / 100)) {
						// 超时停止视频
						mVideoTimeoutCount = 0;
						mButtonVideo.setSelectState(false);
						mApp.mCurrentDevice.setVideoStop();
					}
				} else {
					mVideoTimeoutCount = 0;
				}
				break;
			default:
				break;
			}
		}
	};

	public static int drawWrapString(Canvas canvas, String str, float x,
			float y, float rightMargin, Paint paint) {
		try {
			float[] ws = new float[str.length()];
			float strW = 0f;
			float strH = paint.getTextSize() + 2;
			ArrayList<String> lines = new ArrayList<String>();
			float widthMargin = rightMargin - x;

			// 取得行文字
			paint.getTextWidths(str, ws);
			int start = 0;
			for (int i = 0; i < ws.length; i++) {
				if (str.charAt(i) == '\n') {
					strW = 0f;
					lines.add(str.substring(start, i));
					i++;
					start = i;
				} else if ((strW + ws[i]) > widthMargin) {
					strW = 0f;
					lines.add(str.substring(start, i));
					start = i;
				} else {
					strW += ws[i];
				}
			}
			lines.add(str.substring(start, ws.length));
			for (int i = 0; i < lines.size(); i++) {
				canvas.drawText(lines.get(lines.size() - i - 1), x, y - i
						* strH, paint);
			}
			return lines.size();
		} catch (Exception e) {
			return 0;
		}
	}

	private void showAd(String ad) {
		Paint p = new Paint();
		p.setColor(0xfffeff02);
		int textSize = DensityUtil.dip2px(mContext, 12);
		p.setTextSize(textSize);
		drawWrapString(mCanvas, mAd, DensityUtil.dip2px(mContext, 4),
				mCanvas.getHeight() - DensityUtil.dip2px(mContext, 4),
				mCanvas.getWidth() - DensityUtil.dip2px(mContext, 24), p);
	}

	public void newMessage(Message msg) {
		try {
			if (msg.what == MessageWhat.DeviceMessage) {
				AqDeviceMessage msgObj = (AqDeviceMessage) msg.obj;
				switch (msgObj.mMessageType) {
				case GetStateOk:
					showButtonState();
					showParameter();
					break;
				case NewVideoFrame:
					// 清零视频超时计数器
					mVideoTimeoutCount = 0;
					Bitmap bmp = msgObj.mFrame;
					mPhoto = msgObj.mFrame;
					// 获取画布大小
					int w = mSurfaceView.getWidth();
					int h = mSurfaceView.getHeight();
					double d = (double) w / (double) h;
					int h2 = (int) ((double) bmp.getWidth() / d);
					int h2dt = (bmp.getHeight() - h2) / 2;
					// 显示图像
					mCanvas = mSurfaceHolder.lockCanvas();
					if (mCanvas != null) {
						// 绘制图像帧
						mCanvas.drawBitmap(
								bmp,
								new Rect(0, h2dt, bmp.getWidth() - 1, bmp
										.getHeight() - h2dt), new Rect(0, 0, w,
										h), new Paint());
						// 显示广告
						showAd(mAd);
						mSurfaceHolder.unlockCanvasAndPost(mCanvas);
					}
					break;
				default:
					break;
				}
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			bottom.setVisibility(View.GONE);
			Toast.makeText(DeviceConsoleActivity.this, "one", 0).show();
			// land
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			bottom.setVisibility(View.VISIBLE);
			Toast.makeText(DeviceConsoleActivity.this, "two", 0).show();
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub

	}

}
